<template>
  <!-- 新建文件对话框 -->
  <el-dialog
      title="上传素材"
      v-model="dialogOpen"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="800px"
      @close="handleDialogClose">
    <el-upload class="drag-upload"
               action="#"
               multiple
               drag
               :show-file-list="false"
               :on-remove="handleRemove"
               :before-remove="beforeRemove"
               :on-change="fileChange"
               :http-request="defaultUpload"
    >
      <el-container @click.stop.prevent>
        <el-container>
          <el-aside width="220px" style="overflow: auto;background:#FFFFFF">
            <el-row style="margin-bottom: 20px;">
              <el-select v-model="datas.currentStorageId" placeholder="选择存储" style="width: 200px"
                         @change="handleStorageChange">
                <el-option
                    v-for="item in datas.storageList"
                    :key="item.id"
                    :label="item.storageName"
                    :value="item.id"
                />
              </el-select>
            </el-row>
            <el-row style="overflow: auto;height:280px;">
              <el-tree
                  style="width: 220px"
                  :data="datas.folderList"
                  :props="folderTreeProps"
                  node-key="id"
                  ref="folderTreeList"
                  accordion
                  :current-node-key="datas.currentFolderId"
                  :default-expanded-keys="expandedKeys"
                  highlight-current>
                <template v-slot:default="{ node, data }">
                  <element-tree-line
                      :node="node"
                      :showLabelLine="false"
                      :indent="10">
                    <template v-slot:node-label>
                      <img class="assets-icon" src="../../../assets/images/file/dir.png">
                      <span style="font-size: 12px">
                          {{ node.label }}
                      </span>
                    </template>
                  </element-tree-line>
                </template>
              </el-tree>
            </el-row>
          </el-aside>
          <el-main style="padding:8px 24px">
            <el-row>
              <el-upload action="#"
                         multiple
                         :show-file-list="false"
                         :on-remove="handleRemove"
                         :before-remove="beforeRemove"
                         :on-change="fileChange"
                         :http-request="defaultUpload">
                <el-tooltip class="item" effect="dark" content="支持视频，文档，图片，音频等" placement="right-start">
                  <el-button type="primary" icon="upload" plain>上传知识</el-button>
                </el-tooltip>
              </el-upload>
              <el-upload :on-change="handleChange">
                <el-button type="primary" plain>上传文件夹</el-button>
              </el-upload>
              <el-upload :on-change="handleChange">
                <el-button type="primary" plain>上传压缩包</el-button>
              </el-upload>
              <el-button type="primary" plain>新建文件夹</el-button>
            </el-row>
            <el-row>
              <el-table :data="datas.fileList" stripe style="width: 100%">
                <el-table-column type="index" width="50" label="序号"/>
                <el-table-column prop="name" label="文件名称" width="220">
                  <template #default="scope">
                    <el-tooltip :content="scope.row.name" placement="top">
                      <el-link @click="previewAssets(scope.row.raw.id)">{{ scope.row.name }}</el-link>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column key="percentage" label="上传进度">
                  <template #default="scope">
                    <span v-if="scope.row.percentage < 100">{{ scope.row.percentage }}%</span>
                    <span v-if="scope.row.percentage >= 100"><el-icon class="success-icon"><Finished/></el-icon>成功</span>
                  </template>
                </el-table-column>
                <el-table-column key="operation" label="操作">
                  <template #default="scope">
                    <el-button link type="primary" icon="Delete" @click="deleteFiles(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </el-main>
        </el-container>
      </el-container>
    </el-upload>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleDialogClose">取 消</el-button>
      <el-button
          type="primary"
          :loading="sureBtnLoading"
          @click="handleDialogSure()">确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script setup name="AddAssetsDialog">
import {listStorage} from '@/api/knowledge/storage.js'
import {addAssets, folderTree, getPreviewData} from "@/api/knowledge/assets";
import {uploadFile} from "@/api/knowledge/ossOperate";
import {getElementLabelLine} from 'element-tree-line';
import {h} from "vue";

const ElementTreeLine = getElementLabelLine(h);
const { proxy } = getCurrentInstance();
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  folderIds: {
    type: Array
  },
  storageId: {
    type: String,
    required: true
  }
})
const emits = defineEmits(['reloadList'])
const dialogOpen = ref(false)
const sureBtnLoading = ref(false)

const datas = reactive({
  folderList: [],
  storageList: [],
  fileList: [],
  currentStorageId: "-1",
  currentFolderId: "-1",
})
const expandedKeys = ref([])

const formData = reactive({
  currentStorage: {}
})

const folderTreeProps = {
  children: 'children',
  label: 'title',
}

watch(() => props.visible, (val) => {
  dialogOpen.value = true;
  getStorageList()
  getFolderList()
})

watch(() => props.storageId, (val) => {
  datas.currentStorageId = val;
  if (datas.storageList.value && datas.storageList.value.length > 0) {
    datas.currentStorage = storageList.value.filter(item => item.id === datas.currentStorageId)[0];
  }
}, {immediate: true, deep: true})

watch(() => props.folderIds, () => {
  if (props.folderIds && props.folderIds.length > 0) {
    datas.currentFolderId = props.folderIds[props.folderIds.length - 1].id;
    setExpandedKeys()
  }
}, {immediate: true, deep: true})

function setExpandedKeys() {
  expandedKeys.value.length = 0
  props.folderIds.forEach(item => {
    if (item.id && item.id != "-1") {
      expandedKeys.value.push(item.id)
    }
  })
}

function handleStorageChange() {
  datas.currentFolderId = -1;
  getFolderList()
}

function handleDialogClose() {
  dialogOpen.value = false
  if (datas.fileList && datas.fileList.length > 0) {
    emits("reloadList", datas.fileList.length)
  }
  datas.fileList = [];
}

function handleDialogSure() {
  dialogOpen.value = false
  if (datas.fileList && datas.fileList.length > 0) {
    emits("reloadList", datas.fileList.length)
  }
  datas.fileList = [];
}

function getStorageList() {
  sureBtnLoading.value = true
  listStorage().then((res) => {
    if (res.success) {
      datas.storageList = res.data
      sureBtnLoading.value = false
      if (datas.storageList && datas.storageList.length > 0) {
        formData.currentStorage = datas.storageList.filter(item => item.id === datas.currentStorageId)[0];
      }
    } else {
      proxy.$modal.msgError(res.message)
    }
  })
}

/** 查询资源分类列表 */
function getFolderList() {
  sureBtnLoading.value = true;
  folderTree({storageId: datas.currentStorageId}).then(response => {
    datas.folderList = response.data;
    sureBtnLoading.value = false;
    nextTick(() => {
      proxy.$refs["folderTreeList"].setCurrentKey(datas.currentFolderId)
    })
  });
}

function previewAssets(id) {
  if (!id) {
    return
  }
  getPreviewData(id).then(res => {
    if (res.success && res.data.previewItems && res.data.previewItems.length > 0) {
      console.log("preview:", res.data.title)
      window.open(res.data.previewItems[0].url)
    }
 });
}

function fileChange(file, fileList) {
  if (file.status == 'ready') {
    datas.fileList.push(file)
  }
  console.log(file, fileList)
}

function handleRemove(file, fileList) {
  console.log("remove:" + file)
}

function beforeRemove(file, fileList) {
  console.log("beform remove:" + file)
}

function defaultUpload(file) {
  uploadFile(formData.currentStorage, file).then(res => {
    if (res.data.success) {
      let uploadedFile = res.data.data;
      createAssets(file, uploadedFile)
    } else {
      proxy.$modal.msgError(res.data.message)
    }
  })
}

function createAssets(file, uploadedFile) {
  addAssets({
    title: uploadedFile.originalName,
    size: uploadedFile.size,
    storageId: datas.currentStorageId,
    folderId: datas.currentFolderId,
    objectId: uploadedFile.id,
    objectType: 'assets',
    type: uploadedFile.type,
    ext: uploadedFile.ext
  }).then(res => {
    if (res.success) {
      file.file.id = res.data.id
      file.onSuccess()
    } else {
      proxy.$modal.msgError("新增素材失败")
    }
  })
}
</script>
<style lang="scss" scoped>
@import "@/assets/styles/variables.module.scss";

.dialog-footer {
  margin-bottom: 5px;
}

.assets-icon {
  width: 16px;
  height: 16px;
}

.upload-icon {
  width: 50px;
  height: 50px;
}

.success-icon {
  color: $--color-success;
}

.el-button{
  margin-left:5px;
}
</style>
